import 'dotenv/config';
import http from 'http';
import fs from 'fs/promises';
import url from 'url';
import path from 'path';

//获取当前文件路径
const _filename=url.fileURLToPath(import.meta.url);
const _dirname=path.dirname(_filename);
console.log(_dirname,_filename);

const POST=process.env.POST;

const server = http.createServer(async(req,res)=>{
    try{
        //检查是否为GET请求
        if(req.method==='GET'){
            let filePath;
            if(req.url==='/'){
                filePath =path.join(_dirname,'public','index.html');
               }else if(req.url==='/about'){
                filePath =path.join(_dirname,'public','about.html');
               }else{
                res.writeHead(404,{'Content-Type':'text.html;charset=utf-8'});
                res.end('<h1>页面未找到</h1>');
                return;
               }
        
        const data=await fs.readFile(filePath);
        res.setHeader('Content-Type','text/html;charset=utf-8');
        res.writeHead(200);
        res.end(data);
    }else{
        res.writeHead(400,{'Content-Type':'text.html;charset=utf-8'});
        res.end('<h1>非法请求</h1>');
        }

    }catch(error){
        console.log(error);
        res.writeHead(500,{'Content-Type': 'text/html;charset=utf-8'});
        res.end(`<h1>服务器错误</h1>`);
    }
   
});

server.listen(POST,()=>{
    console.log(`服务器已启动，监听端口${POST}`);
});